package kr.hkit.androidcomplete03.ch28;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import kr.hkit.androidcomplete03.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class HtmlRead extends Activity {
	TextView tv;
	EditText et;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.htmlread);
		tv = (TextView) findViewById(R.id.result);
		et = (EditText) findViewById(R.id.loadhtml);
		findViewById(R.id.down).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				new UrlDown().execute(et.getText().toString());
			}
		});
	}

	class UrlDown extends android.os.AsyncTask<String, Void, String> {
		protected void onPostExecute(String result) {
			tv.setText(result);
		}

		protected String doInBackground(String... strs) {
			StringBuffer sb = new StringBuffer();
			BufferedReader br = null;
			HttpURLConnection con = null;
			String line = null;
			try {
				URL url = new URL(strs[0].toString());
				con = (HttpURLConnection) url.openConnection();
				if (con != null) {
					con.setConnectTimeout(10000);
					con.setUseCaches(false);
					if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
						br = new BufferedReader(new InputStreamReader(
								con.getInputStream()));
					}
				}
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					br.close();
					con.disconnect();
				} catch (Exception e) {
					;
				}
			}
			return sb.toString();
		}
	}
}
